//index.js
const addressUrl = 'https://restapi.amap.com/v3/geocode/regeo'
const app = getApp()
var api = require("../../utils/mr_xu/api_url.js").api
var common = require("../../utils/mr_xu/common.js")

Page({
    data: {
        businessConfig: {
            1: "送车",
            2: "找车",
            3: "找车且送到指定地点"
        },
        statusConfig: common.statusConfig,
        is_examine: "1", //审核模式
        menu: [
            // {
            //     icon: '/image/wzcx2.png',
            //     title: '违章查询',
            //     bgColor: 'linear-gradient(325deg,rgba(45,201,255,1) 0%,rgba(83,241,255,1) 100%);',
            //     url: "./peccancy/add-cart",
            // 	sign:true
            //     // url: "/pages/car-owner/peccancy/cart-list"
            // },
            {
                icon: '/image/xzzc.png',
                title: '我要找车',
                bgColor: 'linear-gradient(141deg,rgba(255,209,45,1) 0%,rgba(255,158,83,1) 100%);',
                url: "/pages/user_side/step1_select_car_status/select_car_status",
                sign: false,
            },
            {
                icon: '/image/lp.png',
                title: '临牌代办',
                bgColor: 'linear-gradient(141deg,rgba(255,209,45,1) 0%,rgba(255,158,83,1) 100%);',
                url: "/pages/linpai/edit-msg",
                sign: false,
            },
            // {
            //     icon: '/image/fx.png',
            //     title: '分销',
            //     bgColor: 'linear-gradient(139deg,rgba(255,186,186,1) 0%,rgba(243,74,74,1) 100%);'
            // },
            {
                icon: '/image/fx.png',
                title: '提档',
                bgColor: 'linear-gradient(139deg,rgba(255,186,186,1) 0%,rgba(243,74,74,1) 100%);',
                url: "/pages/filing/whether-car",
                sign: false,
            },
            {
                icon: '/image/grzx.png',
                title: '个人中心',
                bgColor: 'linear-gradient(147deg,rgba(114,209,255,1) 0%,rgba(22,122,210,1) 100%);',
                url: "/pages/car-owner/personal/personal",
                sign: false,
            },
        ],
        function_list: [

        ],
        findCarItems: [],
        businessConfig: {
            1: "将车送到指定地点",
            2: "仅找车",
            3: "找车且送到自定地点"
        },
    },
    onLoad: function(options) {
        wx.setStorageSync('pre_invite_code', options.scene)
        let user = wx.getStorageSync('user')
        let is_examine = wx.getStorageSync('PROGRAM_VERIFY') //1提审模式 提审模式不验证手机
        if (!user) return
        this.setData(Object.assign({
            user,
            is_examine
        }, options))
        this.getFunctionList()
        this.getFindCarItems()
        this.condition()
    },
    onShow() {
        this.data.startOnShow && this.condition();
        !this.data.startOnShow && this.data.mobile && this.loadData()
    },
    getFunctionList() {

        let that = this

        app.http.post('/car_platform/public/index.php/api/queryAllTypes', {
                data: {
                    type: this.data.type
                },
                type: this.data.type,
                baseUrl: 'https://www.cheapercheaper.top'
            })
            .then(res => {
                console.log(res)
                if (res.success) {
                    let items = []
                    if (res.obj) {
                        for (let i in res.obj) {
                            items.push({
                                icon: '/image/' + res.obj[i].type + '.png',
                                title: res.obj[i].name,
                                bgColor: 'linear-gradient(141deg,rgba(255,209,45,1) 0%,rgba(255,158,83,1) 100%);',
                                url: "/pages/car-owner/function_list/function_list?type=" + res.obj[i].type,
                                sign: false,
                            })
                        }
                    }
                    that.setData({
                        function_list: items,
                    })
                }

            }).catch(res => {
                console.log(res)
                wx.hideLoading()
            })
    },
    condition() {
        let mobile = wx.getStorageSync('mobile')

        if (this.data.is_examine == "1" || (this.data.is_examine != "1" && mobile)) {
            this.setData({
                mobile,
                startOnShow: false,
            })
            this.getLocation().then(this.loadAddress)
            this.loadData()
            return
        }
        wx.showModal({
            title: '温馨提示',
            content: '您暂未绑定手机号,可能会影响您的后续使用',
            showCancel: false,
            confirmColor: '#4db4ff',
            confirmText: '去绑定',
            success: res => {
                if (res.confirm) {
                    this.setData({
                        startOnShow: true
                    })
                    wx.navigateTo({
                        url: '/pages/common/get-phone',
                    })
                }
            }
        })
    },
    loadData() {
        let {
            page = 1, rows = 3, agencyList = []
        } = this.data
        wx.showLoading({
            title: '加载中...',
        })
        app.http.post('rest/quote/queryByList.do', {
            data: {
                page,
                rows,
                orderString: 'updateTime.desc'
            }
        }).then(res => {
            agencyList = res.obj.rows
            this.setData({
                agencyList
            })
            wx.hideLoading()
            wx.stopPullDownRefresh()
        })
    },

    /**
     * 获取经纬度
     */
    getLocation() {
        return new Promise((resolve, reject) => {
            app.toPromise(wx.getStorage, {
                key: "location"
            }).then(res => {
                //经纬度已存在
                return Promise.resolve({
                    longitude: res.data.lng,
                    latitude: res.data.lat,
                })
            }).catch(err => {
                return app.toPromise(wx.getLocation, {
                    type: 'gcj02'
                })
            }).then(res => {
                const location = {
                    lng: res.longitude,
                    lat: res.latitude,
                }
                wx.setStorage({
                    key: 'location',
                    data: location,
                })
                this.setData({
                    location
                })
                resolve()
            }).catch(err => {
                this.setData({ //没有授权
                    addressStatus: 1
                })
                reject()
            })
        })
    },
    /**
     * 点击按钮打开设置授权
     */
    handGetLocation() {
        return new Promise((resolve, reject) => {
            app.toPromise(wx.getSetting).then(res => {
                if (res.authSetting['scope.userLocation']) { //已经授权
                    this.setData({
                        addressStatus: 2
                    })
                    resolve(this.getLocation())
                } else { //没有授权
                    this.setData({
                        addressStatus: 1
                    })
                }
            }).catch(err => {
                this.setData({
                    addressStatus: 1
                })
                reject()
            })
        })

    },

    /**
     * 获取地址
     */
    loadAddress() {
        return app.toPromise(wx.request, {
            url: addressUrl,
            data: {
                key: app.globalData.key,
                location: [this.data.location.lng, this.data.location.lat].join(","),
                poitype: '商务住宅',
                extensions: 'all'
            }
        }).then(res => {
            let data = res.data.regeocode
            try {
                this.setData({
                    address: data.formatted_address,
                    city: data.addressComponent.city,
                    // dtCode: data.addressComponent.adcode,
                    // ctCode: data.addressComponent.adcode.slice(0, 4) + '00',
                    pcCode: data.addressComponent.adcode.slice(0, 3) + '000'
                })
            } catch (err) {
                this.setData({
                    address: data.addressComponent.province + data.addressComponent.city + data.addressComponent.district + data.addressComponent.street,
                    city: data.addressComponent.city
                })
            }
            wx.setStorage({
                key: 'address',
                data: this.data.address,
            })
            wx.setStorage({
                key: 'pcCode',
                data: this.data.pcCode,
            })
        })
    },
    //打开定位地址
    openLocation() {
        wx.openLocation({
            latitude: this.data.location.lat,
            longitude: this.data.location.lng,
            address: this.data.address
        })
    },
    openSetting() {
        this.handGetLocation().then(this.loadAddress)
    },
    onPullDownRefresh() {
        this.loadData()
    },
    onShareAppMessage: function() {

    },
    getFindCarItems() {
        let that = this
        app.http.post(api.apply_order_list, {
                data: {
                    page: 1,
                    rows: 3,
                    orderString: 'createTime.desc'
                }
            })
            .then(res => {
                let rows = res.obj.rows
                for (let i in rows) {
                    let item = rows[i]
                    let showLimit = item.limitTime && common.strtotime(item.limitTime) > (new Date()).getTime() / 1000 ? true : false
                    if (item.limitPrice && showLimit) {
                        rows[i].price = parseInt(item.price) + parseInt(item.limitPrice)
                    }
                    rows[i].showLimit = showLimit
                }
                that.setData({
                    findCarItems: rows
                })
            })
    },
    toFindCarList() {
        wx.navigateTo({
            url: '/pages/user_side/order_list/order_list',
        })
    },
    toFindCarDetail(e) {
        console.log(e)
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/user_side/order_info/order_info?fromway=personal&id=' + id,
        })
    }
})